//**insert package name**
package com.haowan123.qinmeiren.appota2;
import java.io.File;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.mylib.Interface;

/**
 * PicSelectActivity presents image gallery
 * - user can select new images to display within scrolling thumbnail gallery
 * - user can select individual image to display at larger size
 *
 * Sue Smith
 * Mobiletuts+ Tutorial - Importing and Displaying Images with the Android Gallery
 * June 2012
 */
public class PicSelectActivity extends Activity { 
	
	//variable for selection intent
	private final int PICKER = 1;
	//variable to store the currently selected image
	private int currentPic = 0;
	//adapter for gallery view
	private PicAdapter imgAdapt;
	//gallery object
	private Gallery picGallery;
	//image view for larger display
	private ImageView picView;
	private TextView downloadBtn;
	private TextView downloadIndicator;
	private SeekBar downloadProgress;
	private Handler handler;
	private Interface helper;
	private double currentByte;
	private double totalBytes;
	private int stt=-1;
	private ProgressObserver observer = new ProgressObserver();
	
	private ProgressDialog loading;
	private int index=0;
	
    /**
     * instantiate the interactive gallery
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
//    	setThemeApplication(R.drawable.actionbar_color);
    	
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        handler=new Handler();
        //get the large image view
        picView = (ImageView) findViewById(R.id.picture);
        //get the gallery view
        picGallery = (Gallery) findViewById(R.id.gallery);
        //create a new adapter
        imgAdapt = new PicAdapter(this);
        //set the gallery adapter
        picGallery.setAdapter(imgAdapt);
        //set the click listener for each item in the thumbnail gallery
        picGallery.setOnItemClickListener(new OnItemClickListener() {
        	//handle clicks
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
            	//set the larger image view to display the chosen bitmap calling method of adapter class
                picView.setImageBitmap(imgAdapt.getPic(position));
                index=position;
            }
        });
        picView.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent full = new Intent(PicSelectActivity.this, FullScreenshotImageActivity.class);
				full.putExtra(Constants.IMAGE_POSITION, index);
				startActivity(full);
			}
		});
        packageName=getApplicationContext().getPackageName();
        loading=new ProgressDialog(this);
        loading.setMessage("Loading..");
        loading.setCancelable(false);
        downloadProgress=(SeekBar)findViewById(R.id.downloadProgress);
		downloadProgress.setMax(100);
		downloadProgress.setOnTouchListener(new View.OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				return true;
			}});
		downloadBtn=(TextView) findViewById(R.id.downloadBtn);
		downloadIndicator=(TextView) findViewById(R.id.downloadIndicator);
		downloadBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(stt==1){
					downloadBtn.setVisibility(View.GONE);
					downloadProgress.setVisibility(View.VISIBLE);
					new Thread(new Runnable() {
		                public void run() {
		                Log.e("perform download", "perform download");
		                helper.download(packageName,Constants.PATH,"progressFunc","installFunc");
		                }
		            }).start();
				}else if(stt==-1){
					performCheckingDownload();
				}
			}
		});
		
		IntentFilter filter=new IntentFilter();
		filter.addAction(Constants.UPDATE_PROGRESS_ACTION);
		filter.addAction(Constants.DOWNLOAD_COMPLETE_ACTION);
		registerReceiver(observer, filter);
		
		performCheckingDownload();
		
    }

	private void performCheckingDownload() {
		if(checkNetworkAvaliable(this)){
			doGetPics();
		}else{
			AlertDialog.Builder builder=new Builder(this);
			builder.setMessage(getResources().getString(R.string.check_network)).setPositiveButton(getResources().getString(R.string.retry), new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					if(checkNetworkAvaliable(PicSelectActivity.this)){
						dialog.dismiss();
						doGetPics();
					}
				}
			}).setNegativeButton(getResources().getString(R.string.exit), new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					finish();
				}
			}).setCancelable(false).show();
		}
	}
   
	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();
		overridePendingTransition(0,R.anim.push_right_in); 
	}
    @Override
    protected void onDestroy() {
    	unregisterReceiver(observer);
    	super.onDestroy();
    }
    
	private void doGetPics() {
		loading.show();
		handler.postDelayed(new Runnable() {
			
			@Override
			public void run() {
				if(stt!=-1){
					loading.dismiss();
					if(stt==1){
						downloadBtn.setText(getResources().getString(R.string.lbl_app));
					}
				}else{
					handler.postDelayed(this,2000);
				}
			}
		}, 3000);
		helper=new Interface(this);
		stt=helper.init(CommonUtils.getDeviceId(this), packageName, CommonUtils.sdCardPath());
		Log.e("status","stt:"+stt);
		//dismiss loading dialog if able
		if(stt!=-1){
			loading.dismiss();
			if(stt==1){
				downloadBtn.setText(getResources().getString(R.string.lbl_app));
			}
		}
	}
    
	public static boolean checkNetworkAvaliable(Context context) {
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		return cm.getActiveNetworkInfo() != null
				&& cm.getActiveNetworkInfo().isConnectedOrConnecting();
	}
	
    /**
     * Base Adapter subclass creates Gallery view
     * - provides method for adding new images from user selection
     * - provides method to return bitmaps from array
     *
     */
    public class PicAdapter extends BaseAdapter {
    	
    	//use the default gallery background image
        int defaultItemBackground;
        //gallery context
        private Context galleryContext;
        //array to store bitmaps to display
        private Bitmap[] imageBitmaps;
        //placeholder bitmap for empty spaces in gallery
        Bitmap placeholder;
        //constructor
        public PicAdapter(Context c) {
        	//instantiate context
        	galleryContext = c;
        	//create bitmap array
            imageBitmaps  = new Bitmap[8];
            //decode the placeholder image
            //set placeholder as all thumbnail images in the gallery initially
            for(int i=0; i<imageBitmaps.length; i++)
            {
            	placeholder = BitmapFactory.decodeResource(getResources(), ImageResouces.list[i]);
            	imageBitmaps[i]=placeholder;
            }
            //get the styling attributes - use default Andorid system resources
            TypedArray styleAttrs = galleryContext.obtainStyledAttributes(R.styleable.PicGallery);
            //get the background resource
            defaultItemBackground = styleAttrs.getResourceId(
            		R.styleable.PicGallery_android_galleryItemBackground, 0);
            //recycle attributes
            styleAttrs.recycle();
        }
        public int getCount() {
            return imageBitmaps.length;
        }
        //return item at specified position
        public Object getItem(int position) {
            return position;
        }
        //return item ID at specified position
        public long getItemId(int position) {
            return position;
        }
        //get view specifies layout and display options for each thumbnail in the gallery
        public View getView(int _position, View convertView, ViewGroup parent) {
        	index=_position;
        	picView.setImageBitmap(imgAdapt.getPic(_position));
        	//create the view
            ImageView imageView = new ImageView(galleryContext);
            //specify the bitmap at this position in the array
            imageView.setImageBitmap(imageBitmaps[_position]);
            //set layout options
            imageView.setLayoutParams(new Gallery.LayoutParams(300, 200));
            //scale type within view area
            imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
            //set default gallery item background
            imageView.setBackgroundResource(defaultItemBackground);
            //return the view
            return imageView;
        }
        //custom methods for this app
        //helper method to add a bitmap to the gallery when the user chooses one
        public void addPic(Bitmap newPic)
        {
        	//set at currently selected index
        	imageBitmaps[currentPic] = newPic;
        }
        //return bitmap at specified position for larger display
        public Bitmap getPic(int posn)
        {
        	//return bitmap at posn index
        	return imageBitmaps[posn];
        }
    }
    
//    @Override
//	public boolean onCreateOptionsMenu(Menu menu) {
//		// TODO Auto-generated method stub
//		getSupportMenuInflater().inflate(R.menu.activity_details, menu);
//		return true;
//	}
//    
    @Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.more:
			//open more menu
			startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q=pub:GSMVN") ) );
			return true;
		}
		return super.onOptionsItemSelected(item);
    }
    
//    private void setThemeApplication(int drawableId){
////		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
//            BitmapDrawable bg = (BitmapDrawable)getResources().getDrawable(drawableId);
//            bg.setTileModeX(TileMode.REPEAT);
//            getSupportActionBar().setBackgroundDrawable(bg);
////        }
//	}
    
    /**
     * Handle returning from gallery or file manager image selection
     * - import the image bitmap
     */
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	
    	if (resultCode == RESULT_OK) {
    		//check if we are returning from picture selection
            if (requestCode == PICKER) {
 
            	//the returned picture URI
                Uri pickedUri = data.getData();

                //declare the bitmap
                Bitmap pic = null;
                //declare the path string
                String imgPath = "";

                //retrieve the string using media data
                String[] medData = { MediaStore.Images.Media.DATA };
                //query the data
                Cursor picCursor = managedQuery(pickedUri, medData, null, null, null);
                if(picCursor!=null)
                {
                	//get the path string
                    int index = picCursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    picCursor.moveToFirst();
                    imgPath = picCursor.getString(index);
                }
                else
                	imgPath = pickedUri.getPath();
                //if and else handle both choosing from gallery and from file manager
                //if we have a new URI attempt to decode the image bitmap
                if(pickedUri!=null) {

                	//set the width and height we want to use as maximum display
                	int targetWidth = 480;
                	int targetHeight = 480;
                	
                	//sample the incoming image to save on memory resources
                	
                	//create bitmap options to calculate and use sample size
                    BitmapFactory.Options bmpOptions = new BitmapFactory.Options();
                    
                    //first decode image dimensions only - not the image bitmap itself
                    bmpOptions.inJustDecodeBounds = true;
                    BitmapFactory.decodeFile(imgPath, bmpOptions);

                    //work out what the sample size should be

                    //image width and height before sampling
                    int currHeight = bmpOptions.outHeight;
                    int currWidth = bmpOptions.outWidth;
                    
                    //variable to store new sample size
                    int sampleSize = 1;

                    //calculate the sample size if the existing size is larger than target size
                    if (currHeight>targetHeight || currWidth>targetWidth) 
                    {
                    	//use either width or height
                        if (currWidth>currHeight)
                        	sampleSize = Math.round((float)currHeight/(float)targetHeight);
                        else 
                        	sampleSize = Math.round((float)currWidth/(float)targetWidth);
                    }
                    //use the new sample size
                    bmpOptions.inSampleSize = sampleSize;

                    //now decode the bitmap using sample options
                    bmpOptions.inJustDecodeBounds = false;
                    
                    //get the file as a bitmap
                	pic = BitmapFactory.decodeFile(imgPath, bmpOptions);
                	
                	//pass bitmap to ImageAdapter to add to array
                    imgAdapt.addPic(pic);
                    //redraw the gallery thumbnails to reflect the new addition
                    picGallery.setAdapter(imgAdapt);
                    
                    //display the newly selected image at larger size
                    picView.setImageBitmap(pic);
                    //scale options
                    picView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                }
            }
        }
    	//superclass method
    	super.onActivityResult(requestCode, resultCode, data);
    }
    private String packageName;
//    public native int init(String deviceID, String packageName, String SDCard);
//    public native void download(String packageName, String path, String progressFunctionName, String installFunctionName);
    public void updateDownloadProgress(double currentbyte,double totalbytes){
    	if(currentbyte==totalbytes){
    		//finish download
    		downloadProgress.setProgress(0);
    		downloadProgress.setVisibility(View.GONE);
    		downloadBtn.setVisibility(View.VISIBLE);
    		downloadIndicator.setText("");
    		Toast.makeText(PicSelectActivity.this, "Download finished", Toast.LENGTH_SHORT).show();
    	}else{
    		if(totalbytes!=0){
    			downloadProgress.setProgress((int) (currentbyte*100/totalbytes));
    			downloadIndicator.setText(getResources().getString(R.string.download_indicator, (int) (currentbyte*100/totalbytes)));
    		}
    	}
    	
    }
    public void finishDownload(){
    	Intent intent = new Intent(Intent.ACTION_VIEW);
    	intent.setDataAndType(Uri.fromFile(new File(Constants.PATH)),"application/vnd.android.package-archive");
    	startActivity(intent);
    }
    
    private class ProgressObserver extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			if(intent.getAction().equals(Constants.UPDATE_PROGRESS_ACTION)){
				currentByte=intent.getDoubleExtra(Constants.CURRENT_PROGRESS, 0f);
				totalBytes=intent.getDoubleExtra(Constants.TOTAL_PROGRESS, 1f);
				updateDownloadProgress(currentByte, totalBytes);
			}else{
				finishDownload();
			}
		}
    	
    }
    
}
